package com.originskyseed.platform.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.originskyseed.platform.common.annotation.SysLog;
import com.originskyseed.platform.common.api.util.QueryAppUtil;
import com.originskyseed.platform.common.utils.JsonUtils;
import com.originskyseed.platform.core.aspect.annotation.RequiredParams;
import com.originskyseed.platform.core.base.BaseController;
import com.originskyseed.platform.core.base.BaseLocaleResource;
import com.originskyseed.platform.core.base.BasePage;
import com.originskyseed.platform.core.base.BaseResponseBody;
import com.originskyseed.platform.core.common.code.CommonResponseCode;
import com.originskyseed.platform.core.filter.helper.SingleSignOnTokenHelper;
import com.originskyseed.platform.core.util.bean.ExportExcelUtil;
import com.originskyseed.platform.user.i18n.UserResponseMsg;
import com.originskyseed.platform.user.model.Anchor;
import com.originskyseed.platform.user.model.AnchorRelateViolation;
import com.originskyseed.platform.user.model.Family;
import com.originskyseed.platform.user.model.UserInfo;
import com.originskyseed.platform.user.service.IAnchorRelateViolationService;
import com.originskyseed.platform.user.service.IAnchorService;
import com.originskyseed.platform.user.service.IFamilyService;
import com.originskyseed.platform.user.vo.request.AnchorRelateViolationRequestVO;

/**
 * 主播关联违规信息表Controller类（OSI_ANCHOR_RELATE_VIOLATION）
 *
 * @author WuZhuoXi
 */
@Controller
@RequestMapping("/anchorRelateViolation")
@BaseLocaleResource(localeFileName = "i18n_user")
public class AnchorRelateViolationController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(AnchorRelateViolationController.class);

    @DubboReference
    private IAnchorRelateViolationService anchorRelateViolationService;

    @DubboReference
    private IFamilyService familyService;
    @DubboReference
    private IAnchorService anchorService;

    /**
     * 分页查询
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/anchorRelateViolationList.json", method = RequestMethod.POST)
    @RequiredParams(names = {"pageNo", "pageSize"})
    public BaseResponseBody<BasePage<AnchorRelateViolation>> anchorRelateViolationList(HttpServletRequest request) {
        BaseResponseBody<BasePage<AnchorRelateViolation>> result = null;
        try {
            // 请求对象
            AnchorRelateViolationRequestVO requestVO = this.getParameterBean(AnchorRelateViolationRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            String otherAccount =userInfo==null?"": userInfo.getOtherAccount();
            if(userInfo!=null&&userInfo.getType()==11) {
                if (otherAccount == null || StringUtils.isEmpty(otherAccount)) {
                    return new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ANCHOR_BIND_ISNULL.getMsg()), null);
                }
            }
            String familyId = "";
            //Anchor anchor = this.anchorService.selectByAnchorId(userInfo.getOtherAccount());
            // 请求接口查询家族信息
           /* familyId = anchor == null ? "" : anchor.getFamilyId();
            if (familyId == null || StringUtils.isEmpty(familyId)) {
                return new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ANCHOR_BELONG_FAMILY_ISNULL.getMsg()), null);
            }*/
            int pageNo = requestVO.getPageNo();
            int pageSize = requestVO.getPageSize();
            BasePage<AnchorRelateViolation> page = new BasePage<AnchorRelateViolation>(pageNo, pageSize);
            String anchorId = requestVO.getAnchorId() == null ? "" : requestVO.getAnchorId();
            List<String> anchorIdList=this.anchorService.getAnchorId(userInfo);
            if(StringUtils.isNotBlank(anchorId))
            {
                if(!anchorIdList.contains(anchorId))
                {
                    result = new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
                    return result;
                }
            }
            else
            {
                anchorId=StringUtils.join(anchorIdList,",");
            }
            //System.out.println("===anchorId="+anchorId);

            TreeMap<String, Object> paramMap = new TreeMap<>();
            paramMap.put("family_id", familyId);
            paramMap.put("pageNum", pageNo);
            paramMap.put("pageSize", pageSize);

            paramMap.put("anchorId", anchorId);
            String sendTimeStart = requestVO.getSendTimeStart() == null ? "" : requestVO.getSendTimeStart();
            paramMap.put("beginDate", sendTimeStart);
            String sendTimeEnd = requestVO.getSendTimeEnd() == null ? "" : requestVO.getSendTimeEnd();
            paramMap.put("endDate", sendTimeEnd);
            //System.out.println("===paramMap="+paramMap);
            Map resultMap = QueryAppUtil.query("anchorViolationInfoUrl", 1, paramMap);

            Integer code = Integer.parseInt(resultMap.get("code").toString());
            List<AnchorRelateViolation> anchorRelateViolationList = new ArrayList<>();
            if (code == 1) { // 成功
                String data = (String) resultMap.get("data");
                // json字符串转object
                //anchorRelateViolationList = JsonUtils.parseArray(data, AnchorRelateViolation.class);
                JSONArray jsonArray=JSONArray.parseArray(data);
                if(jsonArray!=null)
                {
                    for(int i=0;i<jsonArray.size();i++)
                    {
                        JSONObject jsonObject=jsonArray.getJSONObject(i);
                        String punishStartTime=jsonObject.getString("punishStartTime");
                        String punishEndTime=jsonObject.getString("punishEndTime");
                        if(punishStartTime.equals("-"))
                        {
                            jsonObject.put("punishStartTime",null);
                        }
                        if(punishEndTime.equals("-"))
                        {
                            jsonObject.put("punishEndTime",null);
                        }
                    }
                    anchorRelateViolationList = jsonArray.toJavaList(AnchorRelateViolation.class);
                }
            } else {
                return new BaseResponseBody<BasePage<AnchorRelateViolation>>(false, CommonResponseCode.ERROR.getCode(), (String) resultMap.get("msg"), null);
            }

            page.setResults(anchorRelateViolationList);
            int count = anchorRelateViolationList == null ? 0 : anchorRelateViolationList.size();
            page.setTotalPage(count == 0 ? 0 : count / pageSize + 1);
            page.setTotalRecord(count);
            result = new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_SUCCESS.getMsg()), page);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<BasePage<AnchorRelateViolation>>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_LIST_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 自定义分页
     *
     * @param list
     * @param pageNum
     * @param pageSize
     * @return
     */
    private List<AnchorRelateViolation> startPage(List<AnchorRelateViolation> list, Integer pageNum, Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List<AnchorRelateViolation> pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }

    /**
     * 保存信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/anchorRelateViolationSave.json", method = RequestMethod.POST)
    @RequiredParams(names = {})
    public BaseResponseBody<AnchorRelateViolation> anchorRelateViolationSave(HttpServletRequest request) {
        BaseResponseBody<AnchorRelateViolation> result = null;
        try {
            // 请求对象
            AnchorRelateViolation anchorRelateViolation = this.getParameterBean(AnchorRelateViolation.class);

            if (StringUtils.isNotBlank(anchorRelateViolation.getId())) {
                this.anchorRelateViolationService.updateByPrimaryKey(anchorRelateViolation);
            } else {
                this.anchorRelateViolationService.insertSelective(anchorRelateViolation);
            }
            result = new BaseResponseBody<AnchorRelateViolation>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_SUCCESS.getMsg()), anchorRelateViolation);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<AnchorRelateViolation>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_SAVE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 删除信息
     *
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/anchorRelateViolationDelete.json", method = RequestMethod.POST)
    @RequiredParams(names = {"ids"})
    public BaseResponseBody<Boolean> anchorRelateViolationDelete(HttpServletRequest request) {
        BaseResponseBody<Boolean> result = null;
        try {
            // 请求参数
            String[] ids = this.getParameterArray("ids", new String[]{});

            this.anchorRelateViolationService.deleteByPrimaryKeys(Arrays.asList(ids));
            result = new BaseResponseBody<Boolean>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_SUCCESS.getMsg()), true);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            result = new BaseResponseBody<Boolean>(false, CommonResponseCode.ERROR.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.DATA_DELETE_ERROR.getMsg()), e.getMessage(), null);
        }
        return result;
    }

    /**
     * 主播状态列表_导出
     *
     * @param request
     * @param response
     */
    @ResponseBody
    @RequestMapping(value = "/anchorViolationListToExcel.json")
    @SysLog(module = "主播状态", operationDesc = "主播状态列表信息导出")
    public BaseResponseBody anchorViolationListToExcel(HttpServletRequest request, HttpServletResponse response) {
        BaseResponseBody result = null;
        try {
            // 请求对象
            AnchorRelateViolationRequestVO requestVO = this.getParameterBean(AnchorRelateViolationRequestVO.class);
            UserInfo userInfo = SingleSignOnTokenHelper.getCurrentUserInfo(UserInfo.class);
            //String anchorIds = this.getParameterString("anchorIds",null);
            String otherAccount = userInfo.getOtherAccount();
            if (userInfo == null || otherAccount == null || StringUtils.isEmpty(otherAccount)) {
                return new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ANCHOR_BIND_ISNULL.getMsg()), null);
            }
            String familyId = "";
            Anchor anchor = this.anchorService.selectByAnchorId(userInfo.getOtherAccount());
            //Anchor anchor = this.anchorService.selectByAnchorId(anchorIds);
            // 请求接口查询家族信息
            familyId = anchor == null ? "" : anchor.getFamilyId();
            if (familyId == null || StringUtils.isEmpty(familyId)) {
                return new BaseResponseBody<BasePage<AnchorRelateViolation>>(true, CommonResponseCode.SUCCESS.getCode(), this.getLocaleMessage(this.getClass(), UserResponseMsg.ANCHOR_BELONG_FAMILY_ISNULL.getMsg()), null);
            }
            TreeMap<String, Object> paramMap = new TreeMap<>();
            Family myFamily = new Family();
            paramMap.put("family_id", familyId);
            paramMap.put("pageNum", 1);
            paramMap.put("pageSize", 9999);
            String anchorId = requestVO.getAnchorId() == null ? "" : requestVO.getAnchorId();
            paramMap.put("anchorId", anchorId);
            String sendTimeStart = requestVO.getSendTimeStart() == null ? "" : requestVO.getSendTimeStart();
            paramMap.put("beginDate", sendTimeStart);
            String sendTimeEnd = requestVO.getSendTimeEnd() == null ? "" : requestVO.getSendTimeEnd();
            paramMap.put("endDate", sendTimeEnd);

            Map resultMap = QueryAppUtil.query("anchorViolationInfoUrl", 1, paramMap);
            Integer code = Integer.parseInt(resultMap.get("code").toString());
            List<AnchorRelateViolation> list = new ArrayList<>();
            if (code == 1) { // 成功
                String data = (String) resultMap.get("data");
                // json字符串转object
                list = JsonUtils.parseArray(data, AnchorRelateViolation.class);
            } else {
                return new BaseResponseBody(false, CommonResponseCode.ERROR.getCode(), (String) resultMap.get("msg"), null);
            }
            // excel标题
            String[] title = {"主播ID", "主播昵称", "当前状态", "内容", "违规类型", "发送时间", "处罚开始时间", "处罚结束时间"};
            // excel文件名
            String fileName = "主播状态列表信息" + System.currentTimeMillis() + ".xls";
            // sheet名
            String sheetName = "主播状态信息";
            String[][] values = new String[list.size()][];
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    values[i] = new String[title.length];
                    AnchorRelateViolation obj = list.get(i);
                    values[i][0] = obj.getAnchorId();
                    values[i][1] = obj.getAnchorNickName() == null ? "" : obj.getAnchorNickName();
                    //状态 1警告、2封禁恢复、3永久封禁
                    if (obj.getState() != null) {
                        if (obj.getState() == 1) {
                            values[i][2] = "警告";
                        } else if (obj.getState() == 2) {
                            values[i][2] = "封禁恢复";
                        } else if (obj.getState() == 3) {
                            values[i][2] = "永久封禁";
                        } else {
                            values[i][2] = "";
                        }
                    } else {
                        values[i][2] = "";
                    }
                    values[i][3] = obj.getContent() == null ? "" : obj.getContent();
                    values[i][4] = obj.getType() == null ? "" : obj.getType().toString();
                    values[i][5] = obj.getSendTime() == null ? "" : format.format(obj.getSendTime());
                    values[i][6] = obj.getPunishStartTime() == null ? "" : format.format(obj.getPunishStartTime());
                    values[i][7] = obj.getPunishEndTime() == null ? "" : format.format(obj.getPunishEndTime());
                }
            }
            outPutExcel(response, title, fileName, sheetName, values);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 输出Excel
     *
     * @param response
     * @param title
     * @param fileName
     * @param sheetName
     * @param values
     * @throws IOException
     */
    private void outPutExcel(HttpServletResponse response, String[] title, String fileName, String sheetName, String[][] values) throws IOException {
        // 创建HSSFWorkbook
        HSSFWorkbook wb = ExportExcelUtil.getHSSFWorkbook(sheetName, title, values, null);
        // 将文件存到指定位置
        this.setResponseHeader(response, fileName);
        OutputStream os = response.getOutputStream();
        wb.write(os);
        os.flush();
        os.close();
    }

    /**
     * 发送响应流方法
     *
     * @param response
     * @param fileName
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                logger.error(e.getMessage(), e);
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex.getMessage(), ex);
        }
    }
}
